// 2025/10/18
// 旋转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == nullptr || head->next == nullptr || k == 0)
            return head;
        int n = 0;
        ListNode* cur = head, *tail = nullptr;
        while(cur)
        {
            tail = cur;
            n++;
            cur = cur->next;
        }
        
        n = (n - (k % n)) % n;
        if(n == 0)
            return head;

        ListNode *prev = nullptr;
        cur = head;
        while(n--)
        {
            prev = cur;
            cur = cur->next;
        }
        ListNode* newHead = cur;
        prev->next = nullptr;
        tail->next = head;
        return newHead;
    }
};